// 侧边栏切换
let imageUrl="";
const sidebarToggle = document.getElementById('sidebar-toggle');
const sidebar = document.getElementById('sidebar');

sidebarToggle.addEventListener('click', () => {
  sidebar.classList.toggle('hidden');
  sidebar.classList.toggle('absolute');
  sidebar.classList.toggle('z-40');
  sidebar.classList.toggle('h-screen');
});

// 模态框控制
const houseModal = document.getElementById('house-modal');
const addHouseBtn = document.getElementById('add-house-btn');
const closeModal = document.getElementById('close-modal');
const cancelModal = document.getElementById('cancel-modal');
const modalTitle = document.getElementById('modal-title');

// 打开新增房屋模态框
addHouseBtn.addEventListener('click', () => {
  modalTitle.textContent = '新增房屋';
  houseModal.classList.remove('hidden');
  houseModal.classList.add('flex');
  document.body.style.overflow = 'hidden';
});

// 关闭模态框
function closeHouseModal() {
  houseModal.classList.add('hidden');
  houseModal.classList.remove('flex');
  document.body.style.overflow = '';
}

closeModal.addEventListener('click', closeHouseModal);
cancelModal.addEventListener('click', closeHouseModal);

// 点击模态框外部关闭
houseModal.addEventListener('click', (e) => {
  if (e.target === houseModal) {
    closeHouseModal();
  }
});

// 确认模态框控制
const confirmModal = document.getElementById('confirm-modal');
const cancelConfirm = document.getElementById('cancel-confirm');
const confirmAction = document.getElementById('confirm-action');
const confirmTitle = document.getElementById('confirm-title');
const confirmMessage = document.getElementById('confirm-message');

// 当前操作的房屋ID
let currentHouseId = '';
// 当前操作类型 (上架/下架)
let currentAction = '';

// 打开确认模态框
function openConfirmModal(id, action) {
  currentHouseId = id;
  currentAction = action;
  
  if (action === '下架') {
    confirmTitle.textContent = '确认下架';
    confirmMessage.textContent = '您确定要将此房屋下架吗？下架后用户将无法看到该房屋。';
    confirmAction.classList.remove('btn-success');
    confirmAction.classList.add('btn-danger');
    confirmAction.innerHTML = '<i class="fa fa-ban"></i><span>确认下架</span>';
  } else {
    confirmTitle.textContent = '确认上架';
    confirmMessage.textContent = '您确定要将此房屋上架吗？上架后用户将可以看到并预订该房屋。';
    confirmAction.classList.remove('btn-danger');
    confirmAction.classList.add('btn-success');
    confirmAction.innerHTML = '<i class="fa fa-check-circle"></i><span>确认上架</span>';
  }
  
  confirmModal.classList.remove('hidden');
  confirmModal.classList.add('flex');
  document.body.style.overflow = 'hidden';
}

// 关闭确认模态框
function closeConfirmModal() {
  confirmModal.classList.add('hidden');
  confirmModal.classList.remove('flex');
  document.body.style.overflow = '';
}

cancelConfirm.addEventListener('click', closeConfirmModal);

// 点击确认模态框外部关闭
confirmModal.addEventListener('click', (e) => {
  if (e.target === confirmModal) {
    closeConfirmModal();
  }
});

// 绑定下架按钮事件
document.querySelectorAll('.下架-btn').forEach(btn => {
  btn.addEventListener('click', () => {
    const houseId = btn.getAttribute('data-id');
    openConfirmModal(houseId, '下架');
  });
});

// 绑定上架按钮事件
document.querySelectorAll('.上架-btn').forEach(btn => {
  btn.addEventListener('click', () => {
    const houseId = btn.getAttribute('data-id');
    openConfirmModal(houseId, '上架');
  });
});

// 执行确认操作
confirmAction.addEventListener('click', () => {
  // 这里模拟API请求
  setTimeout(() => {
    closeConfirmModal();
    
    // 更新表格中的状态
    const rows = document.querySelectorAll('tbody tr');
    rows.forEach(row => {
      if (row.querySelector('td:first-child').textContent === `#${currentHouseId}`) {
        const statusCell = row.querySelector('td:nth-child(7)');
        const actionCell = row.querySelector('td:last-child');
        
        if (currentAction === '下架') {
          statusCell.innerHTML = '<span class="px-2 py-1 text-xs font-medium bg-gray-200 text-gray-700 rounded-full">已下架</span>';
          actionCell.innerHTML = `
            <div class="flex items-center gap-2">
              <button class="text-primary hover:text-primary/80 p-1" title="编辑">
                <i class="fa fa-edit"></i>
              </button>
              <button class="text-success hover:text-success/80 p-1上架-btn" data-id="${currentHouseId}" title="上架">
                <i class="fa fa-check-circle"></i>
              </button>
              <button class="text-gray-600 hover:text-gray-800 p-1" title="查看详情">
                <i class="fa fa-eye"></i>
              </button>
            </div>
          `;
          
          // 重新绑定新出现的上架按钮事件
          actionCell.querySelector('.上架-btn').addEventListener('click', () => {
            openConfirmModal(currentHouseId, '上架');
          });
          
          showToast('success', '操作成功', `房屋 #${currentHouseId} 已成功下架`);
        } else {
          statusCell.innerHTML = '<span class="px-2 py-1 text-xs font-medium bg-success/10 text-success rounded-full">已上架</span>';
          actionCell.innerHTML = `
            <div class="flex items-center gap-2">
              <button class="text-primary hover:text-primary/80 p-1" title="编辑">
                <i class="fa fa-edit"></i>
              </button>
              <button class="text-danger hover:text-danger/80 p-1下架-btn" data-id="${currentHouseId}" title="下架">
                <i class="fa fa-ban"></i>
              </button>
              <button class="text-gray-600 hover:text-gray-800 p-1" title="查看详情">
                <i class="fa fa-eye"></i>
              </button>
            </div>
          `;
          
          // 重新绑定新出现的下架按钮事件
          actionCell.querySelector('.下架-btn').addEventListener('click', () => {
            openConfirmModal(currentHouseId, '下架');
          });
          
          showToast('success', '操作成功', `房屋 #${currentHouseId} 已成功上架`);
        }
      }
    });
  }, 500);
});

// 保存房屋信息
const saveHouseBtn = document.getElementById('save-house');
saveHouseBtn.addEventListener('click', () => {
  // 这里模拟表单验证和提交
  const houseName = document.querySelector('input[name="name"]').value;

  if (!houseName) {
    showToast('error', '保存失败', '请输入房屋名称');
    return;
  }

  // 模拟API请求
  setTimeout(() => {
    $(function () {alert($("input[name='facility']:checked").val())
      $.ajax({
        url: baseUrl + "/admin/save",
        type: "post",
        headers: {
          // 'Content-Type': "application/json;charset=UTF-8"
          "content-type":"application/x-www-form-urlencoded"
        },
        data: {
          name: $("#name").val(),
          place: $("#city").val() + $("#address").val(),
          price: $("#price").val(),
          area: $("#area").val(),
          type: $("#type").val(),
          decorateSituation: $("#description").val(),
          pic: imageUrl,
          state: $("input[name='status']:checked").val(),
          device: $("input[name='facility']:checked").val()
        },
        success: function (res) {
          console.log(res)
          if(res.code=="0"){
            console.log("成功添加房源数据");
            closeHouseModal();
            showToast('success', '保存成功', modalTitle.textContent === '新增房屋' ? '房屋已成功添加' : '房屋信息已更新');

            // 重置表单
            document.getElementById('house-form').reset();
            loadInit("");
          }else{
            console.log("房源数据添加失败");
          }
        },
        error: function (res) {

          console.log(res)
        }
      });
      // closeHouseModal();
      // showToast('success', '保存成功', modalTitle.textContent === '新增房屋' ? '房屋已成功添加' : '房屋信息已更新');

      // 重置表单
      // document.getElementById('house-form').reset();
    }, 800);
  });
});
// 图片上传预览
const imageUpload = document.getElementById('image-upload');
const imagePreview = document.getElementById('image-preview');

imageUpload.addEventListener('change', (e) => {
  if (e.target.files.length > 0) {
    imagePreview.classList.remove('hidden');
    // 实际项目中应该根据上传的文件显示预览
    // 这里只是简单显示示例图片
    // 获取文件输入元素
    // const fileInput = $(imageUpload); // 假设你的文件输入框id为fileInput

// 创建FormData对象并添加文件
    const formData = new FormData();
    formData.append('file', imageUpload.files[0]); // 'file'为后端接收的参数名
    //formData.append('extraParam', 'value'); // 可添加其他参数
debugger
    $.ajax({
      url: baseUrl + "file/upload",
      type: "POST",
      data: formData,

      // 必须配置项
      contentType: false, // 必须false才会自动带上正确的Content-Type
      processData: false, // 必须false才会避免jQuery将FormData转为字符串

      // 可选：上传进度提示
      xhr: function() {
        const xhr = new XMLHttpRequest();
        xhr.upload.addEventListener('progress', function(e) {
          if (e.lengthComputable) {
            const percent = Math.round((e.loaded / e.total) * 100);
            console.log('上传进度:', percent + '%');
            // 可在此处更新进度条UI
          }
        }, false);
        return xhr;
      },

      success: function(res) {
        console.log(res)
        if (res.code == "0") {
          console.log('上传成功:', res);
          imageUrl=res.file;
          // 处理成功逻辑，例如显示预览图
          $('#backImg').attr('src',baseUrl+ res.file+"?time="+new Date().getTime());
        } else {
          console.error('上传失败:');
          // alert('上传失败: ' + res.message);
        }
      },

      error: function(xhr, status, error) {
        console.error('请求异常:', status, error);
        alert('上传请求失败，请检查网络连接');
      }
    });
  }
});

// 移除预览图片
imagePreview.addEventListener('click', (e) => {
  if (e.target.closest('button')) {
    e.target.closest('.relative').remove();
    if (imagePreview.children.length === 0) {
      imagePreview.classList.add('hidden');
    }
  }
});

// 通知提示框
const toast = document.getElementById('toast');
const toastIcon = document.getElementById('toast-icon');
const toastTitle = document.getElementById('toast-title');
const toastMessage = document.getElementById('toast-message');
const closeToast = document.getElementById('close-toast');

function showToast(type, title, message) {
  // 设置提示类型
  if (type === 'success') {
    toastIcon.className = 'text-success mt-0.5';
    toastIcon.innerHTML = '<i class="fa fa-check-circle text-xl"></i>';
  } else if (type === 'error') {
    toastIcon.className = 'text-danger mt-0.5';
    toastIcon.innerHTML = '<i class="fa fa-times-circle text-xl"></i>';
  } else if (type === 'warning') {
    toastIcon.className = 'text-warning mt-0.5';
    toastIcon.innerHTML = '<i class="fa fa-exclamation-triangle text-xl"></i>';
  }
  
  // 设置内容
  toastTitle.textContent = title;
  toastMessage.textContent = message;
  
  // 显示提示
  toast.classList.remove('translate-x-full');
  
  // 3秒后自动关闭
  setTimeout(() => {
    hideToast();
  }, 3000);
}

function hideToast() {
  toast.classList.add('translate-x-full');
}

closeToast.addEventListener('click', hideToast);
